<?php
/**
 * @describe 调用阿里云工具类上传文件封装
 *
 * @author wlx
 * @since 2018/11/2
 */

namespace App\Services;


use Illuminate\Support\Facades\Log;

class StoreTool
{
    /**
     * 文件上传到Oss
     *
     * @param string $filePath
     * @param string $ossKey
     * @param bool $needOptions
     *
     * @return string
     */
    public static function uploadFileToOssByFilePath($filePath, $ossKey, $needOptions = false)
    {
        try {
            if (!file_exists($filePath) || empty($ossKey)) {
                return '';
            }
            $options = [];
            if ($needOptions) {
                $options = OssTool::getContentTypeOptionsByFilePath($filePath);
            }
            OSSTool::publicUpload('', $ossKey, $filePath, $options);
            return $ossKey;
        } catch (\Exception $e) {
            $arr = [
                '[file]' . $e->getFile(),
                '[line]' . $e->getLine(),
                '[error]' . $e->getMessage()
            ];
            $message = '[message]阿里云上传失败' . implode(' ', $arr);
            Log::error($message, ['filePath' => $filePath]);

            return '';
        }
    }

    /**
     * 生成通用的ossKey
     *
     * @param string $filePath
     * @param string $fileTypeName
     *
     * @return string
     */
    public static function generateGenericOssKeyByFilePath($filePath, $fileTypeName = '')
    {
        if (!file_exists($filePath)) return '';
        $ext = self::getFileExt($filePath);
        if (empty($ext)) return '';
        $year_str = date('Y');
        $month_str = date('m');
        $date_str = date('d');
        $uuid = date('YmdHis') . substr(implode(null, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
        $fileName = $uuid . '.' . $ext;
        $oss_key = $year_str . '/' . $month_str . '/' . $date_str . '/' . $fileName;
        if ($fileTypeName) {
            $oss_key = $fileTypeName . '/' . $oss_key;
        }
        return $oss_key;
    }

    /**
     * 获取文件后缀
     *
     * @param $filePath
     *
     * @return mixed|string
     */
    public static function getFileExt($filePath)
    {
        if ($filePath) {
            return pathinfo($filePath, PATHINFO_EXTENSION);
        }
        return '';
    }

}